<template>
  <div>
    <div class="login-container">
      <h2>login page</h2>
      <el-form
        ref="formLogin"
        :model="form"
        :rules="rules"
        label-width="70px"
        class="form"
      >
        <el-form-item label="邮箱" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" />
        </el-form-item>
        <el-form-item label="验证码" prop="captcha">
          <el-input v-model="form.captcha" style="width: 200px" />
          <img class="send-btn" :src="captcha" alt="" @click="reCaptcha" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin">登陆</el-button>
          <el-button type="success" @click="handleRegister">注册</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import md5 from 'md5'
export default {
  layout: 'login',
  data() {
    return {
      form: {
        username: '',
        password: '',
        captcha: '',
      },
      captcha: '/api/captcha?_t' + new Date().getTime(),
      rules: {
        username: [
          { required: true, message: '请输入邮箱' },
          { type: 'email', message: '请输入正确的邮箱格式' },
        ],
        captcha: {
          required: true,
          pattern: /^\w{4}$/,
          message: '请输入验证码',
        },
        password: {
          required: true,
          pattern: [/^[w_-]{6-12}$/g],
          message: '请输入6-12位的密码',
        },
      },
    }
  },
  methods: {
    reCaptcha() {
      this.captcha = '/api/captcha?_t' + new Date().getTime()
    },
    handleRegister() {
      this.$router.push('/user/register')
    },
    handleLogin() {
      this.$refs.formLogin.validate(async (valid) => {
        if (valid) {
          const obj = {
            email: this.form.username,
            passwd: md5(this.form.password),
            captcha: this.form.captcha,
          }
          const ret = await this.$http.post('/user/login', obj)
          console.log('handleLogin ret', ret)
          if (ret.code === 0) {
            this.$message('登陆成功!')
            this.$router.push('/')
          } else {
            console.log('登陆失败')
            this.$message(ret.message)
          }
        }
      })
      // this.$http.post()
    }
  },
}
</script>
